package basicelement;


import istar.IElement;
import istar.agent.IstarJadeAgent;
import istar.behaviour.IstarBehaviour;
import istar.impl.AbstractBasicTask;
import istar.onto.IstarOntology;
import jade.content.lang.Codec;
import jade.content.lang.sl.SLCodec;
import jade.content.onto.Ontology;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.Behaviour;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;

import log.Log;

import com.rapidminer.RapidMiner;
import com.rapidminer.example.Attribute;
import com.rapidminer.example.Example;
import com.rapidminer.example.ExampleSet;
import com.rapidminer.operator.IOContainer;
import com.rapidminer.operator.Operator;
import com.rapidminer.operator.io.ExampleSource;
import com.rapidminer.tools.OperatorService;

public class SeekQuotation extends AbstractBasicTask{

	private boolean log = true;
	//private String pathToFile = "D:\\Documents and Settings\\csid\\Meus documentos\\rm_workspace\\VALE5\\VALE5-JAN15-TEST-MAX-MAI-JUN-2009.aml";
	//private String pathToFile = "D:\\Documents and Settings\\csid\\workspace\\Fanxaria\\file\\dataset\\VALE5-JAN15-TEST-MAX-MAI-JUN-2009.aml";
	private HashMap<String, String> quotations = null;
	private boolean done = false;
	
	public SeekQuotation() {
		super("SeekQuotation");
	}
	
	/*
	public SeekQuotation(String modelPath) {
		super("SeekQuotation"); 
		pathToFile = modelPath;
	}
	*/
	@Override
	public Behaviour getBehaviour() {
		//return new myBehaviour((IstarJadeAgent)this.getOwner(), this);
		return new myBehaviour(this);
	}
	
	private class myBehaviour extends IstarBehaviour{

		//AbstractBasicTask task;
		boolean isFile = false;
		String testModel = "";
		
		
		public myBehaviour(AbstractBasicTask _task){
			super(_task);
			//task = _task;
			//this.setElement(_task);
			this.setBehaviourName("SeekQuotation");

		}
		
		@Override
		public void myAction() throws Exception {
			
			BufferedReader in = new BufferedReader(new FileReader(((IstarJadeAgent)myAgent).configurationPath));
		    String str;
		    while ((str = in.readLine()) != null) {
		        if (str.startsWith("TestModelFile=")){
		        	testModel = str.substring(14);
		        }
		    }
		    in.close();

			
            IElement main = (IElement)((IstarJadeAgent)myAgent).getKnowledgeElement(this.getElement().getExecutionNumber(), this.getElement().getMain().getId()) ;
            String simulationStep= "";
            // getting quotation parameter
            
            ACLMessage msg = ((IstarJadeAgent)myAgent).getWorkingMessages().get(getElement().getExecutionNumber());
				
			//ArrayList<String> contentList = (ArrayList<String>)msg.getContentObject();
			//for (int i=0;i<contentList.size();i++){
			String contentElement = (String)main.getContent().get(0);
			if (contentElement.contains("<simulation_step=")){
				int init = contentElement.indexOf("<simulation_step=") + 17;
				while (contentElement.charAt(init)!='>'){
					simulationStep += contentElement.charAt(init);
					init++;
				}
			}
			//}

			Example example = this.getLastQuotationFromFile(simulationStep, testModel);
			
			ArrayList<String> response = new ArrayList<String>();
			//response.add(example.toString());
			AID senderAID = msg.getSender();
			ACLMessage reply = new ACLMessage(ACLMessage.INFORM);
			Codec codec = new SLCodec();
			Ontology ontology = IstarOntology.getInstance();
			reply.setLanguage(codec.getName());
			reply.setOntology(ontology.getName());

			reply.setConversationId(msg.getConversationId());
			reply.addReceiver(senderAID);
            reply.setContentObject(example);
            myAgent.send(reply);
            done = true;
				
		}
		
		private Example getLastQuotationFromFile(String step, String pathToFile){
			Operator testSourceMax = null;
			try {
				testSourceMax = OperatorService.createOperator(ExampleSource.class);
			} catch (Exception e) { 
					// invoke init before using the OperatorService
					//RapidMiner.init(true, false, false, false);
					RapidMiner.init();
					System.out.println(this.getBehaviourName()+ " rodou RapidMiner.init()");
					try {
						testSourceMax = OperatorService.createOperator(ExampleSource.class);
					} catch (Exception e2) {
						e.printStackTrace();
					}
			}

				try {
					testSourceMax.setParameter("attributes", pathToFile);
					IOContainer containerMax = testSourceMax.apply(new IOContainer());
					ExampleSet resultSet = containerMax.get(ExampleSet.class);
					Attribute quotationTime= resultSet.getAttributes().getId();
					//RapidMiner.quit(0);
					return resultSet.getExample(new Integer(step));
					
					// add operator to process
					//process.getRootOperator().addOperator(testSourceMax);
				} catch (Exception e) { 
					e.printStackTrace ();
					return null;
				}	
		}
		

		public int myOnEnd() {
			if (done){
				log("Agent name="+ myAgent.getName() +" ending behaviour:"+ this.getBehaviourName());
				return 1;
			}
			else
				return 0;
		}
		

		@Override
		public boolean done() {
			return true;
		}
		
		
		
		/*
		private void loadIModel(String _pathToFile) {
			File modelFile;
			try {
				modelFile = new File(_pathToFile);
				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
				DocumentBuilder db = dbf.newDocumentBuilder();
				Document doc = db.parse(modelFile);
				doc.getDocumentElement().normalize();
				
				NodeList ndListFile= doc.getDocumentElement().getChildNodes();
				for (int i = 0; i < ndListFile.getLength(); i++) {
					Node ndFile = ndListFile.item(i);
					if (ndFile.getNodeType() == Node.ELEMENT_NODE) {
						NodeList ndLst = ndFile.getChildNodes();
						for (int j = 0; j < ndLst.getLength(); j++) {
							Node elmntNode = ndLst.item(j);
							if (elmntNode.getNodeType() == Node.ELEMENT_NODE) {
								Element elmnt = (Element)elmntNode;
								String elementType = elmnt.getTagName();
								System.out.println(elementType);
							}
						}
					}
				}
			}
			catch (Exception e) {
					e.printStackTrace();
				}

			}
		 */
		
	}
	

}
